package by.averianov.discounta.webapp.app;


import javax.inject.Inject;

import org.apache.wicket.Session;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.injection.Injector;
import org.apache.wicket.request.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.averianov.discounta.datamodel.UserAccount;
import by.averianov.discounta.datamodel.UserProfile;
import by.averianov.discounta.datamodel.enums.AccessGroup;
import by.averianov.discounta.services.UserService;

public class BasicAuthenticationSession extends AuthenticatedWebSession {

    private static final Logger LOGGER = LoggerFactory.getLogger(BasicAuthenticationSession.class);

    //public static final String ROLE_SIGNED_IN = "SIGNED_IN";
    private UserProfile userProfile;

    private Roles resultRoles;

    @Inject
    private UserService userService;

    public BasicAuthenticationSession(final Request request) {
        super(request);
        Injector.get().inject(this);
    }

    public static BasicAuthenticationSession get() {
        return (BasicAuthenticationSession) Session.get();
    }

    @Override
    public boolean authenticate(final String userEmail, final String password) {
        boolean authenticationResult = false;
        final UserAccount account = userService.getAccountByEmail(userEmail);
		if (account != null && account.getUserPassword().equals(password)) {
			this.userProfile = userService.getUserProfile(account.getId());
			authenticationResult = true;
		}
		return authenticationResult;
		
		
        /*try {
            authenticationResult = authenticationManager.authenticate(userName, password);
            this.user = userName;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            LOGGER.error("Internal error on attempt to authenticate user.", e);
            return false;
        }
        return authenticationResult;*/
    }

    @Override
    public Roles getRoles() {
    	if (isSignedIn() && (resultRoles == null)) {
			resultRoles = new Roles();
			//List<AccessGroup> roles = userService.getAccessGroup(userProfile.getId());
			AccessGroup roles = userProfile.getAccessGroup();
			//for (AccessGroup role : roles) {
				resultRoles.add(roles.name());
			//}
		}
		return resultRoles;
    	
    	
        /*if (isSignedIn() && (resultRoles == null)) {
            resultRoles = new Roles();
            //resultRoles.add(ROLE_SIGNED_IN);
            resultRoles.addAll(authenticationManager.resolveRoles(userName));
        }
        return resultRoles;*/
    }

    @Override
    public void signOut() {
        super.signOut();
        userProfile = null;
    }

    public UserProfile getUserProfile() {
        return userProfile;
    }

}
